# coding=utf-8

from common.risk.model import RiskyCard, RiskyUser, RiskyIP
from common.utils import track_logging
from common.utils.db import list_object, get, upsert, delete
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)


@sql_wrapper
def get_risky_card(id):
    return get(RiskyCard, id)


@sql_wrapper
def get_risky_card_by_num(card_num, mch_id):
    # mch_id为0表示可以匹配所有mch
    card = RiskyCard.query.filter(
        RiskyCard.card_num == card_num).filter(
        RiskyCard.status == 1).filter(
        RiskyCard.mch_id.in_([0, mch_id])).first()
    return card


@sql_wrapper
def upsert_risky_card(info, id=None):
    return upsert(RiskyCard, info, id)


@sql_wrapper
def create_risky_card(info, id=None):
    return upsert(RiskyCard, info, id)


@sql_wrapper
def list_risky_card(query_dct):
    return list_object(query_dct, RiskyCard)


@sql_wrapper
def delete_risky_card(id):
    delete(RiskyCard, id)


@sql_wrapper
def get_risky_user(id):
    return get(RiskyUser, id)


@sql_wrapper
def upsert_risky_user(info, id=None):
    return upsert(RiskyUser, info, id)


@sql_wrapper
def list_risky_user(query_dct):
    return list_object(query_dct, RiskyUser)


@sql_wrapper
def get_user_ip(risk_user_id):
    items = RiskyIP.query.filter(RiskyIP.risk_user_id == risk_user_id).limit(20)
    return items
